package com.lastoffer2.activity;

import java.text.SimpleDateFormat;
import java.util.List;

import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;
import com.lastoffer2.R;
import com.lastoffer2.R.layout;
import com.lastoffer2.R.menu;
import com.lastct.dao.Offer;
import com.lastoffer2.listener.MapImageOnClickListener;
import com.lastoffer2.util.DateUtilExtra;
import com.lastoffer2.util.GeoUtil;
import com.lastoffer2.util.JSONConnector;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.opengl.Visibility;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class DetailOfferActivity extends Activity implements LocationListener {
	
	private int idOffer;
	protected LocationManager locationManager;
	protected String provider;
	protected Location location;
	protected Location previousLocation;
	protected Criteria criteria;
	Offer offer;
	private ProgressDialog pd;
	SimpleDateFormat formatterLong = new SimpleDateFormat("EEE, d MMM HH:mm");
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detail_offer);
		Bundle b = getIntent().getExtras();
		idOffer = b.getInt("IdOffer");
		Log.i("MyApp", "START DETAIL");
		
		TextView labelPiuInfo=(TextView) findViewById(R.id.labelPiuInfo);
    	labelPiuInfo.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				TextView textViewPiuInfo=(TextView) findViewById(R.id.textViewPiuInfo);
				if(textViewPiuInfo.getVisibility()==View.VISIBLE)
					textViewPiuInfo.setVisibility(View.GONE);
				else
					textViewPiuInfo.setVisibility(View.VISIBLE);
			}
		});
		
		// Get the location manager
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		// Define the criteria how to select the locatioin provider -> use
		// default
		criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_COARSE);
		provider = locationManager.getBestProvider(criteria, false);
		for (String providerTmp : locationManager.getAllProviders()) {
			Location locationTmp = locationManager.getLastKnownLocation(providerTmp);
			if (location != null && location.getTime() + 30000 >= System.currentTimeMillis()) {
				if (locationTmp != null
						&& locationTmp.getAccuracy() > location.getAccuracy()) {
					location = locationTmp;
				}
			} else {
				location = locationTmp;
			}
		} 
		 
		 
		if (offer == null) {
			// Start a new thread that will download all the data
			new DownloadTask()
					.execute("Any parameters my download task needs here");
					Log.i("MyApp", "START PD");
			this.pd = ProgressDialog.show(this, "Working..",
					"Downloading Data...", true, false);
		}
		
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_detail_offer, menu);
		return true;
	}
	
	private class DownloadTask extends AsyncTask<String, Void, Object> {
        protected Object doInBackground(String... args) {
            Log.i("MyApp", "Background thread starting");
            
            Offer result=JSONConnector.getOffer(idOffer);
            
            Log.i("MyApp", "RESULT OBJECT "+result);
            if(result!=null){
	            try {
	            	if (location != null && !location.equals(previousLocation)){
			        	Location dest = new Location(location);
			        	dest.setLatitude(result.getLatitude());
			        	dest.setLongitude(result.getLongitude());
			        	result.setDistance(GeoUtil.getDistance(location, dest));
			        	
		        	}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					 e.printStackTrace();
				}
            }
            return result;
        }

        protected void onPostExecute(Object result) {
            // Pass the result data back to the main activity
        	if(result!=null){
	        	
        		DetailOfferActivity.this.offer = (Offer) result;
	        	
	        	//set title
	        	TextView title=(TextView) findViewById(R.id.detail_title_textView);
	        	title.setText(offer.getName());

	        	//set short description
	        	TextView description=(TextView) findViewById(R.id.detail_description);
	        	description.setText(offer.getShortDescription());
	        	
	        	//set data scadenza offerta
	        	TextView data=(TextView) findViewById(R.id.detail_data_scadenza);
	        	data.setText(formatterLong.format(offer.getDataFinePrenotazione()));

	        	//set long description
	        	TextView textViewPiuInfo=(TextView) findViewById(R.id.textViewPiuInfo);
	        	textViewPiuInfo.setText(offer.getDescription());
	        	
	        	//set image
	        	ImageView imageView=(ImageView) findViewById(R.id.imageView011);
	        	if(!offer.getImage().isEmpty())
	        		UrlImageViewHelper.setUrlDrawable(imageView, offer.getImage());
	        	
	        	//calculate and set posti disponibili
	        	TextView postiDisponibiliTV=(TextView) findViewById(R.id.textView_postiDisponibili);
	        	int postiDisponibili=offer.getNumMax()-offer.getNumAccepted();
	        	if(postiDisponibili<=0){
	        		postiDisponibili=0;
	        	}
	        	postiDisponibiliTV.setText(""+postiDisponibili);

	        	//set map with onclicklistener
	        	ImageView mapView=(ImageView) findViewById(R.id.imageMap);
	        	UrlImageViewHelper.setUrlDrawable(mapView, GeoUtil.getGMapUrl(400, 350, offer.getLatitude(), offer.getLongitude(), "O", false));
	        	mapView.setOnClickListener(new MapImageOnClickListener(DetailOfferActivity.this,offer.getLatitude(), offer.getLongitude()));
	        	
	        	//set distance
	        	TextView distance=(TextView) findViewById(R.id.distanzaTextView);
	        	distance.setText(offer.getDistance());
	        	
	        	 
        	}
        	if (DetailOfferActivity.this.pd != null) {
        		DetailOfferActivity.this.pd.dismiss();
        	}
        }
   }

	@Override
	public void onLocationChanged(Location location) {
		if (location == null) {
			Toast.makeText(this, "Retrived location....updating...",
					Toast.LENGTH_SHORT).show();
		}
		Toast.makeText(this, "changed location "+location,
				Toast.LENGTH_SHORT).show();
		this.previousLocation = this.location;
		this.location = location;
		// Start a new thread that will download all the data
		
			if(offer!=null){
	        	Location dest = new Location(location);
	        	dest.setLatitude(offer.getLatitude());
	        	dest.setLongitude(offer.getLongitude());
	        	TextView distance=(TextView) findViewById(R.id.distanzaTextView);
	        	try {
					distance.setText(GeoUtil.getDistance(location, dest));
	    		} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					distance.setText(""+location.distanceTo(dest)+" m");
				}
				Log.i("DETAIL", "new diistance "+distance.getText());
			}
		
	}

	@Override
	public void onProviderDisabled(String provider) {
		Toast.makeText(this, "Disabled provider " + provider,
				Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onProviderEnabled(String provider) {
		Toast.makeText(this, "Enabled provider " + provider,
				Toast.LENGTH_SHORT).show();
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		Toast.makeText(this, "status changed " + provider,
				Toast.LENGTH_SHORT).show();
		// TODO Auto-generated method stub
	}   
	

}
